package com.example.springbootwxminiappintegrat.util.pay.wx;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class WxHttpClientConfig {

    @Bean
    public HttpClient wxHttpClient(
            @Value("${mchid}") String mchid,
            @Value("${mchSerialNo}") String mchSerialNo,
            PrivateKey merchantPrivateKey,
            AutoUpdateCertificatesVerifier autoUpdateCertificatesVerifier) {
        return WechatPayHttpClientBuilder.create()
                .withMerchant(mchid, mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(autoUpdateCertificatesVerifier)).build();
    }

    /**
     * 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3密钥）
     */
    @Bean
    public AutoUpdateCertificatesVerifier autoUpdateCertificatesVerifier(
            PrivateKey merchantPrivateKey,
            @Value("${mchid}") String mchid,
            @Value("${mchSerialNo}") String mchSerialNo,
            @Value("${v3Key}") String v3Key) throws UnsupportedEncodingException {
        return new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(mchid, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
                v3Key.getBytes("utf-8"));
    }

    /**
     * 加载商户私钥（privateKey：私钥字符串）
     */
    @Bean
    public PrivateKey merchantPrivateKey(@Value("${privateKey}") String privateKey)
            throws UnsupportedEncodingException {
        return PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
    }
}
